﻿using Common.Contract.Authentication.Record;
using Common.Contract.Customer.Record;
using Common.Contract.SystemConfig.Record;
using Customer.Core.Data;
using Customer.Model.Interface;
using Customer.Model.Model;
using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;

namespace Customer.Provider
{
    public class CustomerProvider : GenericProvider, ICustomerProvider
    {
        #region Customer Portfolio and new
        public Customers RetrieveCustomerByCif(string cif)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.Customers
                        where x.Cif == cif
                        select x;
            return query.FirstOrDefault();
        }

        public List<CustomerInfoDescription> RetrieveAllCustomerInfoCode()
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerInfoDescriptions
                        select x;
            return query.ToList();
        }
        public CustomerContact RetrieveCustomerContactByCif(string cif)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerContacts
                        where x.Cif == cif
                        select x;
            return query.FirstOrDefault();
        }
        public ProfitAbility RetrieveToiAccumulatedCustByCif(string cif)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.ToiAccumulateds
                        where x.Cif == cif && x.ProfitType == 1
                        select x;
            return query.FirstOrDefault();
        }
        public ProfitAbility RetrieveToiAvgBalAccumulatedCustByCif(string cif)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.ToiAccumulateds
                        where x.Cif == cif && x.ProfitType == 2
                        select x;
            return query.FirstOrDefault();
        }
        public List<ProductCardRawDaily> RetrieveCustomerCardByCif(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.ProductCardRaws
                        where x.Cif == textSearch.Cif
                        select x;
            totalRecord = query.Count();
            query = query.OrderBy(x => x.CardNumber);
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        public List<CustomerRegion> RetrieveCustomerDepositByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0, DateTime? fromDate = null, string group = null, string grouptype = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerRegions
                        where x.Deposits.Count > 0
                        select x;

            IQueryable<CustomerBranch> querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new CustomerBranch { Cust = x, Branch = y });
            querySearch = FilterCustomerRegionByCondition(querySearch, dao, textSearch, lang);

            List<string> listBalance = new List<string>();
            decimal fromValue = 0, toValue = 0;

            listBalance = textSearch.Balance.Split('-').ToList();
            fromValue = !string.IsNullOrEmpty(listBalance.FirstOrDefault()) ? decimal.Parse(listBalance.FirstOrDefault()) : 0;
            toValue = !string.IsNullOrEmpty(listBalance.LastOrDefault()) ? decimal.Parse(listBalance.LastOrDefault()) : (decimal)1e18;
            query = querySearch.OrderBy(x => new { x.Branch.Region, x.Branch.BranchId, x.Cust.Dao }).Select(x => x.Cust);
            if (!string.IsNullOrEmpty(group) && !string.IsNullOrEmpty(grouptype))
            {
                List<string> listFilter = grouptype.Split(',').ToList();
                if (group.Equals("0"))
                {
                    query = query.Where(x => listFilter.All(y => x.Deposits.Count(z => z.ProductName.Contains(y)) > 0));
                    if (listBalance.Count == 2)
                    {
                        query = query.Select(x => new { cust = x, sumBal = x.Deposits.Where(z => listFilter.Contains(z.ProductName)).Sum(y => y.BalQd) }).Where(x => x.sumBal >= fromValue && (toValue == 0 ? true : x.sumBal <= toValue)).Select(x => x.cust);
                    }
                }
                else
                {
                    query = query.Where(x => listFilter.All(y => x.Deposits.Count(z => z.ChuongTrinhSp.Contains(y)) > 0));

                    if (listBalance.Count == 2)
                    {
                        query = query.Select(x => new { cust = x, sumBal = x.Deposits.Where(z => listFilter.Contains(z.ChuongTrinhSp)).Sum(y => y.BalQd) }).Where(x => x.sumBal >= fromValue && (toValue == 0 ? true : x.sumBal <= toValue)).Select(x => x.cust);
                    }
                }
            }
            else
            {
                query = query.Select(x => new { cust = x, sumBal = x.Deposits.Sum(y => y.BalQd) }).Where(x => x.sumBal >= fromValue && (toValue == 0 ? true : x.sumBal <= toValue)).Select(x => x.cust);
            }
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<CustomerRegion> RetrieveCustomerLoanByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0, string group = null, string grouptype = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerRegions
                        where x.Loans.Count(y => y.Channel == "OTHER") > 0
                        select x;
            IQueryable<CustomerBranch> querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new CustomerBranch { Cust = x, Branch = y });
            querySearch = FilterCustomerRegionByCondition(querySearch, dao, textSearch, lang);

            List<string> listBalance = new List<string>();
            decimal fromValue = 0, toValue = 0;
            listBalance = textSearch.Balance.Split('-').ToList();
            fromValue = !string.IsNullOrEmpty(listBalance.FirstOrDefault()) ? decimal.Parse(listBalance.FirstOrDefault()) : 0;
            toValue = !string.IsNullOrEmpty(listBalance.LastOrDefault()) ? decimal.Parse(listBalance.LastOrDefault()) : (decimal)1e18;

            query = querySearch.OrderBy(x => new { x.Branch.Region, x.Branch.BranchId, x.Cust.Dao }).Select(x => x.Cust);

            List<string> listFilter = grouptype.Split(',').ToList();
            if (!string.IsNullOrEmpty(group) && !string.IsNullOrEmpty(grouptype))
            {
                if (group.Equals("0"))
                {
                    query = query.Where(x => listFilter.All(y => x.Loans.Count(z => z.CtUudaiVay.Contains(y)) > 0));
                    query = query.Select(x => new { cust = x, sumBal = x.Loans.Where(z => listFilter.Contains(z.CtUudaiVay)).Sum(y => y.BalQd) }).Where(x => x.sumBal >= fromValue && (toValue == 0 ? true : x.sumBal <= toValue)).Select(x => x.cust);
                }
                else if (group.Equals("1"))
                {
                    query = query.Where(x => listFilter.All(y => x.Loans.Count(z => z.ChuongTrinhSp.Contains(y)) > 0));
                    query = query.Select(x => new { cust = x, sumBal = x.Loans.Where(z => listFilter.Contains(z.ChuongTrinhSp)).Sum(y => y.BalQd) }).Where(x => x.sumBal >= fromValue && (toValue == 0 ? true : x.sumBal <= toValue)).Select(x => x.cust);
                }
                else
                {
                    query = query.Where(x => listFilter.All(y => x.Loans.Count(z => z.NhomSpLoan.Contains(y)) > 0));
                    query = query.Select(x => new { cust = x, sumBal = x.Loans.Where(z => listFilter.Contains(z.NhomSpLoan)).Sum(y => y.BalQd) }).Where(x => x.sumBal >= fromValue && (toValue == 0 ? true : x.sumBal <= toValue)).Select(x => x.cust);
                }
            }
            else
            {
                query = query.Select(x => new { cust = x, sumBal = x.Loans.Sum(y => y.BalQd) }).Where(x => x.sumBal >= fromValue && (toValue == 0 ? true : x.sumBal <= toValue)).Select(x => x.cust);
            }
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        public List<CustomerRegion> RetrieveCustomerCardByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0, DateTime? fromDate = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerRegions
                        where x.Cards.Count > 0
                        select x;

            IQueryable<CustomerBranch> querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new CustomerBranch { Cust = x, Branch = y });
            querySearch = FilterCustomerRegionByCondition(querySearch, dao, textSearch, lang);
            List<string> listBalance = new List<string>();
            if (!string.IsNullOrEmpty(textSearch.Balance))
            {
                double fromValue = 0, toValue = 0;
                listBalance = textSearch.Balance.Split(';').ToList();
                fromValue = !string.IsNullOrEmpty(listBalance.FirstOrDefault()) ? double.Parse(listBalance.FirstOrDefault()) : 0;
                toValue = !string.IsNullOrEmpty(listBalance.LastOrDefault()) ? double.Parse(listBalance.LastOrDefault()) : (double)1e18;
                querySearch = querySearch.Where(x => x.Cust.Cards.FirstOrDefault().Balance >= fromValue && x.Cust.Cards.FirstOrDefault().Balance <= toValue);
            }
            List<string> listNoOfCard = new List<string>();
            if (!string.IsNullOrEmpty(textSearch.NoOfCard))
            {
                double fromValue1 = 0, toValue1 = 0;
                listNoOfCard = textSearch.NoOfCard.Split(';').ToList();
                fromValue1 = !string.IsNullOrEmpty(listNoOfCard.FirstOrDefault()) ? double.Parse(listNoOfCard.FirstOrDefault()) : 0;
                toValue1 = !string.IsNullOrEmpty(listNoOfCard.LastOrDefault()) ? double.Parse(listNoOfCard.LastOrDefault()) : (double)1e18;
                querySearch = querySearch.Where(x => x.Cust.Cards.FirstOrDefault().NoOfCard >= fromValue1 && x.Cust.Cards.FirstOrDefault().NoOfCard <= toValue1);
            }
            List<string> listScored = new List<string>();
            if (!string.IsNullOrEmpty(textSearch.ScoredCard))
            {
                double fromValue2 = 0, toValue2 = 0;
                listScored = textSearch.ScoredCard.Split(';').ToList();
                fromValue2 = !string.IsNullOrEmpty(listScored.FirstOrDefault()) ? double.Parse(listScored.FirstOrDefault()) : 0;
                toValue2 = !string.IsNullOrEmpty(listScored.LastOrDefault()) ? double.Parse(listScored.LastOrDefault()) : (double)1e18;
                querySearch = querySearch.Where(x => x.Cust.Cards.FirstOrDefault().ScoredCard >= fromValue2 && x.Cust.Cards.FirstOrDefault().ScoredCard <= toValue2);
            }
            query = querySearch.OrderBy(x => new { x.Branch.Region, x.Branch.BranchId, x.Cust.Dao }).Select(x => x.Cust);
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<ProductI2B> RetrieveCustomerI2bByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0, DateTime? fromDate = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.ProductI2Bs
                        select x;
            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                query = query.Where(x => textSearch.Region.ToUpper().Contains(x.Region.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                query = query.Where(x => textSearch.Branch.ToUpper().Contains(x.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Dao) && textSearch.Dao.Trim() != "null")
            {
                query = query.Where(x => textSearch.Dao.Contains(x.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName) && textSearch.DaoName.Trim() != "null")
            {
                query = query.Where(x => textSearch.DaoName.Contains(x.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Cif))
            {
                query = query.Where(x => x.Cif.Contains(textSearch.Cif));
            }
            if (!string.IsNullOrEmpty(textSearch.CustName))
            {
                query = query.Where(x => x.CusName.Contains(textSearch.CustName));
            }
            if (!string.IsNullOrEmpty(textSearch.Industry))
            {
                query = lang.Equals("vi") ? query.Where(x => x.IndustryName.Contains(textSearch.Industry)) : query.Where(x => x.IndustryNameEn.Contains(textSearch.Industry));
            }
            if (!string.IsNullOrEmpty(textSearch.CusOpenDate))
            {
                List<string> listFilter = textSearch.CusOpenDate.Split('-').ToList();
                FromDateCompare = DateTime.ParseExact(listFilter.FirstOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                ToDateCompare = DateTime.ParseExact(listFilter.LastOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                query = query.Where(x => x.CusOpenDate.Value >= FromDateCompare && x.CusOpenDate.Value <= ToDateCompare);
            }
            if (fromDate != null && fromDate.HasValue)
            {
                query = query.Where(x => x.CusOpenDate > fromDate);
            }
            totalRecord = query.Count();

            query = query.OrderBy(x => new { x.Region, x.BranchId, x.Dao });
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<CustomerRegion> RetrieveCustomerPosByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0, DateTime? fromDate = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerRegions
                        where x.Poss.Count > 0
                        select x;

            IQueryable<CustomerBranch> querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new CustomerBranch { Cust = x, Branch = y });
            querySearch = FilterCustomerRegionByCondition(querySearch, dao, textSearch, lang);
            query = querySearch.OrderBy(x => new { x.Branch.Region, x.Branch.BranchId, x.Cust.Dao }).Select(x => x.Cust);
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<ProductTrade> RetrieveCustomerTradeByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0, DateTime? fromDate = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.ProductTrades
                        select x;

            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                query = query.Where(x => textSearch.Region.ToUpper().Contains(x.ZoneIdSme.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                query = query.Where(x => textSearch.Branch.ToUpper().Contains(x.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Dao) && textSearch.Dao.Trim() != "null")
            {
                query = query.Where(x => textSearch.Dao.Contains(x.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName) && textSearch.DaoName.Trim() != "null")
            {
                query = query.Where(x => textSearch.DaoName.Contains(x.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Cif))
            {
                query = query.Where(x => x.Cif.Contains(textSearch.Cif));
            }
            if (!string.IsNullOrEmpty(textSearch.CustName))
            {
                query = query.Where(x => x.CustName.Contains(textSearch.CustName));
            }
            if (!string.IsNullOrEmpty(textSearch.Industry))
            {
                query = lang.Equals("vi") ? query.Where(x => x.IndustryName.Contains(textSearch.Industry)) : query.Where(x => x.IndustryNameEn.Contains(textSearch.Industry));
            }
            if (!string.IsNullOrEmpty(textSearch.CusOpenDate))
            {
                List<string> listFilter = textSearch.CusOpenDate.Split('-').ToList();
                FromDateCompare = DateTime.ParseExact(listFilter.FirstOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                ToDateCompare = DateTime.ParseExact(listFilter.LastOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                query = query.Where(x => x.CusOpenDate.Value >= FromDateCompare && x.CusOpenDate.Value <= ToDateCompare);
            }

            if (fromDate != null && fromDate.HasValue)
            {
                query = query.Where(x => x.CusOpenDate > fromDate);
            }
            totalRecord = query.Count();
            query = query.OrderBy(x => new { x.ZoneIdSme, x.BranchCode, x.Dao });
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<ProductChuoi> RetrieveCustomerChuoiByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0, DateTime? fromDate = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.ProductChuois
                        select x;
            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                query = query.Where(x => textSearch.Region.ToUpper().Contains(x.ZoneIdSme.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                query = query.Where(x => textSearch.Branch.ToUpper().Contains(x.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Dao) && textSearch.Dao.Trim() != "null")
            {
                query = query.Where(x => textSearch.Dao.Contains(x.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName) && textSearch.DaoName.Trim() != "null")
            {
                query = query.Where(x => textSearch.DaoName.Contains(x.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Cif))
            {
                query = query.Where(x => x.CustId.Contains(textSearch.Cif));
            }
            if (!string.IsNullOrEmpty(textSearch.CustName))
            {
                query = query.Where(x => x.CusName.Contains(textSearch.CustName));
            }
            if (!string.IsNullOrEmpty(textSearch.Industry))
            {
                query = lang.Equals("vi") ? query.Where(x => x.IndustryName.Contains(textSearch.Industry)) : query.Where(x => x.IndustryNameEn.Contains(textSearch.Industry));
            }
            if (!string.IsNullOrEmpty(textSearch.CusOpenDate))
            {
                List<string> listFilter = textSearch.CusOpenDate.Split('-').ToList();
                FromDateCompare = DateTime.ParseExact(listFilter.FirstOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                ToDateCompare = DateTime.ParseExact(listFilter.LastOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                query = query.Where(x => x.CusOpenDate.Value >= FromDateCompare && x.CusOpenDate.Value <= ToDateCompare);
            }

            if (fromDate != null && fromDate.HasValue)
            {
                query = query.Where(x => x.CusOpenDate > fromDate);
            }
            totalRecord = query.Count();
            query = query.OrderBy(x => new { x.ZoneIdSme, x.BranchCode, x.Dao });
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<string> RetrieveListProductDeposit(string dao, string group, DateTime? fromDate = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.ProductDeposits
                        select x;
            if (group.Equals("1"))
            {
                return query.Select(x => x.ChuongTrinhSp).Distinct().OrderBy(name => name).ToList();
            }
            else
            {
                return query.Select(x => x.ProductName).Distinct().OrderBy(name => name).ToList();
            }
        }

        public List<string> RetrieveListProductLoan(string dao, string group)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.ProductLoans
                        select x;
            List<string> result;
            switch (group)
            {
                case "1":
                    result = query.Select(x => x.ChuongTrinhSp).Distinct().OrderBy(name => name).ToList();
                    break;
                case "0":
                    result = query.Select(x => x.CtUudaiVay).Distinct().OrderBy(name => name).ToList();
                    break;
                default:
                    result = query.Select(x => x.NhomSpLoan).Distinct().OrderBy(name => name).ToList();
                    break;
            }
            return result;
        }

        public List<ProductI2BDetail> RetrieveListProductI2BDetailByCif(out int totalRecord, string cif, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.ProductI2BDetails
                        where x.CustCif == cif
                        select x;
            totalRecord = query.Count();
            query = query.OrderBy(x => x.OpenDate);
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<NewLending> RetrieveNewLendingByCif(string cif)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.NewLendings
                        where x.Cif == cif
                        select x;
            return query.ToList();
        }
        #endregion
        #region New Customer
        public List<CustomerLowValue> RetrieveCustomerLowValueByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0, DateTime? fromDate = null, string type = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerLowValues
                        select x;
            var querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { Cust = x, Branch = y });

            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Region.ToUpper().Contains(x.Branch.Region.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Branch.ToUpper().Contains(x.Cust.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Dao))
            {
                querySearch = querySearch.Where(x => x.Cust.Dao.Contains(textSearch.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName))
            {
                querySearch = querySearch.Where(x => x.Cust.DaoName.Contains(textSearch.DaoName));
            }
            if (!string.IsNullOrEmpty(textSearch.Cif))
            {
                querySearch = querySearch.Where(x => x.Cust.Cif.Contains(textSearch.Cif));
            }
            if (!string.IsNullOrEmpty(textSearch.CustName))
            {
                querySearch = querySearch.Where(x => x.Cust.CusName.Contains(textSearch.CustName));
            }
            if (!string.IsNullOrEmpty(textSearch.Industry))
            {
                querySearch = lang.Equals("vi") ? querySearch.Where(x => x.Cust.IndustryName.Contains(textSearch.Industry)) : querySearch.Where(x => x.Cust.IndustryNameEn.Contains(textSearch.Industry));
            }
            if (!string.IsNullOrEmpty(textSearch.CusOpenDate))
            {
                List<string> listFilter = textSearch.CusOpenDate.Split('-').ToList();
                FromDateCompare = DateTime.ParseExact(listFilter.FirstOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                ToDateCompare = DateTime.ParseExact(listFilter.LastOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                querySearch = querySearch.Where(x => x.Cust.CusOpenDate >= FromDateCompare && x.Cust.CusOpenDate <= ToDateCompare);
            }
            query = querySearch.OrderBy(x => new { x.Branch.Region, x.Branch.BranchId, x.Cust.Dao }).Select(x => x.Cust);
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<Customers> RetrieveCustomerByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0, DateTime? fromDate = null, string type = null)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.Customers
                        select x;

            var querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { cust = x, branch = y });
            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Region.ToUpper().Contains(x.branch.Region.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Branch.ToUpper().Contains(x.cust.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(dao.Team) && dao.DaoSubOrdinatorList != null && dao.DaoSubOrdinatorList.Count > 0)
            {
                if (string.IsNullOrEmpty(textSearch.RequestStatus) || !textSearch.RequestStatus.Equals("Y"))
                {
                    querySearch = querySearch.Where(x => dao.DaoSubOrdinatorList.Contains(x.cust.Dao));
                }
            }
            if (!string.IsNullOrEmpty(textSearch.Dao) && textSearch.Dao.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Dao.Contains(x.cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName) && textSearch.DaoName.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.DaoName.Contains(x.cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Cif))
            {
                querySearch = querySearch.Where(x => x.cust.Cif.Contains(textSearch.Cif));
            }
            if (!string.IsNullOrEmpty(textSearch.CustName))
            {
                querySearch = querySearch.Where(x => x.cust.CusName.Contains(textSearch.CustName));
            }
            if (!string.IsNullOrEmpty(textSearch.TextSearchByCif))
            {
                querySearch = querySearch.Where(x => x.cust.Cif.Contains(textSearch.TextSearchByCif));
            }
            if (!string.IsNullOrEmpty(textSearch.SubSegment))
            {
                querySearch = querySearch.Where(x => x.cust.SubSegment.Equals(textSearch.SubSegment));
            }
            if (!string.IsNullOrEmpty(textSearch.Industry))
            {
                querySearch = lang.Equals("vi") ? querySearch.Where(x => x.cust.IndustryName.Contains(textSearch.Industry)) : querySearch.Where(x => x.cust.IndustryNameEn.Contains(textSearch.Industry));
            }
            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.CusOpenDate))
            {
                List<string> listFilter = textSearch.CusOpenDate.Split('-').ToList();
                FromDateCompare = DateTime.ParseExact(listFilter.FirstOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                ToDateCompare = DateTime.ParseExact(listFilter.LastOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                querySearch = querySearch.Where(x => x.cust.CusOpenDate.Value >= FromDateCompare && x.cust.CusOpenDate.Value <= ToDateCompare);
            }
            if (!string.IsNullOrEmpty(textSearch.CusStatus) && textSearch.CusStatus != "2")
            {
                querySearch = querySearch.Where(x => x.cust.CusStatus.Equals(textSearch.CusStatus));
            }
            if (!string.IsNullOrEmpty(textSearch.BusinessStatus) && textSearch.BusinessStatus != "2")
            {
                querySearch = querySearch.Where(x => x.cust.BusinessStatus.Equals(textSearch.BusinessStatus));
            }
            query = querySearch.OrderBy(x => new { x.branch.Region, x.branch.BranchId, x.cust.Dao }).Select(x => x.cust);
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        public List<CustomerNeedUpdateInfo> RetrieveCustomerNeedToUpdateInfoByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerNeedUpdateInfos
                        select x;
            var querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { Cust = x, Branch = y });

            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Region.ToUpper().Contains(x.Branch.Region.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Branch.ToUpper().Contains(x.Cust.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(dao.Team) && dao.DaoSubOrdinatorList != null && dao.DaoSubOrdinatorList.Count > 0)
            {
                querySearch = querySearch.Where(x => dao.DaoSubOrdinatorList.Contains(x.Cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Dao) && textSearch.Dao.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Dao.Contains(x.Cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName) && textSearch.DaoName.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.DaoName.Contains(x.Cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Cif))
            {
                querySearch = querySearch.Where(x => x.Cust.Cif.Contains(textSearch.Cif));
            }
            if (!string.IsNullOrEmpty(textSearch.CustName))
            {
                querySearch = querySearch.Where(x => x.Cust.CusName.Contains(textSearch.CustName));
            }
            if (!string.IsNullOrEmpty(textSearch.Industry))
            {
                querySearch = lang.Equals("vi") ? querySearch.Where(x => x.Cust.IndustryName.Contains(textSearch.Industry)) : querySearch.Where(x => x.Cust.IndustryNameEn.Contains(textSearch.Industry));
            }

            if (!string.IsNullOrEmpty(textSearch.CusOpenDate))
            {
                List<string> listFilter = textSearch.CusOpenDate.Split('-').ToList();
                FromDateCompare = DateTime.ParseExact(listFilter.FirstOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                ToDateCompare = DateTime.ParseExact(listFilter.LastOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                querySearch = querySearch.Where(x => x.Cust.CusOpenDate.Value >= FromDateCompare && x.Cust.CusOpenDate.Value <= ToDateCompare);
            }
            List<string> listBalance = new List<string>();
            if (!string.IsNullOrEmpty(textSearch.Balance))
            {
                double fromValue = 0, toValue = 0;
                listBalance = textSearch.Balance.Split('-').ToList();
                fromValue = !string.IsNullOrEmpty(listBalance.FirstOrDefault()) ? double.Parse(listBalance.FirstOrDefault()) : 0;
                toValue = !string.IsNullOrEmpty(listBalance.LastOrDefault()) ? double.Parse(listBalance.LastOrDefault()) : (double)1e18;
                querySearch = querySearch.Where(x => x.Cust.NoInfoNeedUpdate >= fromValue && x.Cust.NoInfoNeedUpdate <= toValue);
            }

            query = querySearch.OrderBy(x => new { x.Branch.Region, x.Branch.BranchId, x.Cust.Dao }).Select(x => x.Cust);
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<CustomerNeedUpdateInfoRaw> RetrieveCustomerNeedToUpdateInfoRawByCif(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerNeedUpdateInfoRaws.Include(x => x.CustomerInfoCode)
                        select x;
            query = query.Where(x => x.T24Cif.Equals(textSearch.Cif));

            query = query.OrderBy(x => x.T24Cif);
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        #endregion
        #region Customer priority
        public List<CustomerPriority> RetrieveCustomerPriorityByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerPriorities
                        where x.CustTypeName.ToUpper() != "OTHERS"
                        select x;
            var querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { cust = x, branch = y });
            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Region.ToUpper().Contains(x.branch.Region.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Branch.ToUpper().Contains(x.cust.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Dao) && textSearch.Dao.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Dao.Contains(x.cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName) && textSearch.DaoName.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.DaoName.Contains(x.cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Cif))
            {
                querySearch = querySearch.Where(x => x.cust.Cif.Contains(textSearch.Cif));
            }
            if (!string.IsNullOrEmpty(textSearch.CustName))
            {
                querySearch = querySearch.Where(x => x.cust.CusName.Contains(textSearch.CustName));
            }
            if (!string.IsNullOrEmpty(textSearch.Industry))
            {
                querySearch = lang.Equals("vi") ? querySearch.Where(x => x.cust.IndustryName.Contains(textSearch.Industry)) : querySearch.Where(x => x.cust.IndustryNameEn.Contains(textSearch.Industry));
            }
            List<string> listBalance = new List<string>();
            if (!string.IsNullOrEmpty(textSearch.Balance))
            {
                double fromValue = 0, toValue = 0;
                listBalance = textSearch.Balance.Split('-').ToList();
                fromValue = !string.IsNullOrEmpty(listBalance.FirstOrDefault()) ? double.Parse(listBalance.FirstOrDefault()) : 0;
                toValue = !string.IsNullOrEmpty(listBalance.LastOrDefault()) ? double.Parse(listBalance.LastOrDefault()) : (double)1e18;
                querySearch = querySearch.Where(x => x.cust.Toi.Value >= fromValue && x.cust.Toi.Value <= toValue);
            }
            if (!string.IsNullOrEmpty(textSearch.Balance1))
            {
                double fromValue1 = 0, toValue1 = 0;
                listBalance = textSearch.Balance1.Split('-').ToList();
                fromValue1 = !string.IsNullOrEmpty(listBalance.FirstOrDefault()) ? double.Parse(listBalance.FirstOrDefault()) : 0;
                toValue1 = !string.IsNullOrEmpty(listBalance.LastOrDefault()) ? double.Parse(listBalance.LastOrDefault()) : (double)1e18;
                querySearch = querySearch.Where(x => x.cust.Toi2015.Value >= fromValue1 && x.cust.Toi2015.Value <= toValue1);
            }
            if (!string.IsNullOrEmpty(textSearch.Balance2))
            {
                decimal fromValue2 = 0, toValue2 = 0;
                listBalance = textSearch.Balance1.Split('-').ToList();
                fromValue2 = !string.IsNullOrEmpty(listBalance.FirstOrDefault()) ? decimal.Parse(listBalance.FirstOrDefault()) : 0;
                toValue2 = !string.IsNullOrEmpty(listBalance.LastOrDefault()) ? decimal.Parse(listBalance.LastOrDefault()) : (decimal)1e18;
                querySearch = querySearch.Where(x => x.cust.NhomNo >= fromValue2 && x.cust.NhomNo <= toValue2);
            }
            if (!string.IsNullOrEmpty(textSearch.CusStatus))
            {
                switch (textSearch.CusStatus)
                {
                    case "0":
                        querySearch = querySearch.Where(x => x.cust.CustTypeName.ToUpper().Equals("SME SILVER"));
                        break;
                    case "1":
                        querySearch = querySearch.Where(x => x.cust.CustTypeName.ToUpper().Equals("SME GOLD"));
                        break;
                    case "2":
                        querySearch = querySearch.Where(x => x.cust.CustTypeName.ToUpper().Equals("SME DIAMOND"));
                        break;
                    default:
                        break;
                }

            }
            query = querySearch.OrderBy(x => new { x.branch.Region, x.branch.BranchId, x.cust.Dao }).Select(x => x.cust);
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        #endregion
        #region Customer sub-segment
        public CountCustSegmentRecord CountCustSubSegment(UserRecord dao)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.Customers
                        select x;
            switch (dao.GroupIdentifier)
            {
                case "1":
                    break;
                case "2":
                    query = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { cust = x, branch = y }).Where(x => x.branch.Region == dao.Zone).Select(x => x.cust);
                    break;
                case "3":
                    query = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { cust = x, branch = y }).Where(x => x.branch.BranchNameSme == dao.Branch).Select(x => x.cust);
                    break;
                case "4":
                    query = query.Where(x => x.Dao.ToUpper() == dao.Dao.ToUpper());
                    break;
                default:
                    break;
            }
            if (dao.GroupIdentifier == "1")
            {
                query = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { cust = x, branch = y }).OrderBy(x => new { x.branch.Region, x.branch.BranchId, x.cust.Dao }).Select(x => x.cust);
            }
            else
            {
                query = query.OrderBy(x => new { x.BranchId, x.Dao });
            }
            var result = new CountCustSegmentRecord
            {
                CountSme = String.Format("{0:#,##0}", query.Where(x => x.SubSegment.ToUpper().Equals("SME")).Count()),
                CountMme = String.Format("{0:#,##0}", query.Where(x => x.SubSegment.ToUpper().Equals("MME")).Count()),
                CountMsme = String.Format("{0:#,##0}", query.Where(x => x.SubSegment.ToUpper().Equals("MSME")).Count()),
            };
            return result;
        }
        #endregion
        #region CustomerFeedback
        public List<CustomerFeedback> RetrieveCustomerFeedbackByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerFeedbacks
                        select x;
            var querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { cust = x, branch = y });
            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Region.ToUpper().Contains(x.branch.Region.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Branch.ToUpper().Contains(x.cust.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(dao.Team) && dao.DaoSubOrdinatorList != null && dao.DaoSubOrdinatorList.Count > 0)
            {
                querySearch = querySearch.Where(x => dao.DaoSubOrdinatorList.Contains(x.cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Dao) && textSearch.Dao.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Dao.Contains(x.cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName) && textSearch.DaoName.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.DaoName.Contains(x.cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Cif))
            {
                querySearch = querySearch.Where(x => x.cust.Cif.Contains(textSearch.Cif));
            }
            if (!string.IsNullOrEmpty(textSearch.CustName))
            {
                querySearch = querySearch.Where(x => x.cust.CusName.Contains(textSearch.CustName));
            }
            if (!string.IsNullOrEmpty(textSearch.Industry))
            {
                querySearch = lang.Equals("vi") ? querySearch.Where(x => x.cust.IndustryName.Contains(textSearch.Industry)) : querySearch.Where(x => x.cust.IndustryNameEn.Contains(textSearch.Industry));
            }
            List<string> listBalance = new List<string>();
            if (!string.IsNullOrEmpty(textSearch.Balance))
            {
                decimal fromValue = 0, toValue = 0;
                listBalance = textSearch.Balance.Split('-').ToList();
                fromValue = !string.IsNullOrEmpty(listBalance.FirstOrDefault()) ? decimal.Parse(listBalance.FirstOrDefault()) : 0;
                toValue = !string.IsNullOrEmpty(listBalance.LastOrDefault()) ? decimal.Parse(listBalance.LastOrDefault()) : (decimal)1e18;
                querySearch = querySearch.Where(x => x.cust.Complaint >= fromValue && x.cust.Complaint <= toValue);
            }
            if (!string.IsNullOrEmpty(textSearch.Balance1))
            {
                decimal fromValue1 = 0, toValue1 = 0;
                listBalance = textSearch.Balance1.Split('-').ToList();
                fromValue1 = !string.IsNullOrEmpty(listBalance.FirstOrDefault()) ? decimal.Parse(listBalance.FirstOrDefault()) : 0;
                toValue1 = !string.IsNullOrEmpty(listBalance.LastOrDefault()) ? decimal.Parse(listBalance.LastOrDefault()) : (decimal)1e18;
                querySearch = querySearch.Where(x => x.cust.Compliment >= fromValue1 && x.cust.Compliment <= toValue1);
            }
            query = querySearch.OrderBy(x => new { x.branch.Region, x.branch.BranchId, x.cust.Dao }).Select(x => x.cust);
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public List<CustomerFeedbackDetail> RetrieveCustomerFeedbackDetailByCif(out int totalRecord, string cif, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerFeedbackDetails
                        where x.Cif == cif
                        select x;
            totalRecord = query.Count();
            query = query.OrderBy(x => x.Createdtime);
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        #endregion

        #region Customer freedom

        public List<CustomerFreedom> RetrieveCustomerFreedomByDao(out int totalRecord, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerFreedoms
                        select x;
            var querySearch = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { cust = x, branch = y });
            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Region.ToUpper().Contains(x.branch.Region.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Branch.ToUpper().Contains(x.cust.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Dao) && textSearch.Dao.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.Dao.Contains(x.cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName) && textSearch.DaoName.Trim() != "null")
            {
                querySearch = querySearch.Where(x => textSearch.DaoName.Contains(x.cust.Dao));
            }
            if (!string.IsNullOrEmpty(textSearch.Cif))
            {
                querySearch = querySearch.Where(x => x.cust.Cif.Contains(textSearch.Cif));
            }
            if (!string.IsNullOrEmpty(textSearch.CustName))
            {
                querySearch = querySearch.Where(x => x.cust.CusName.Contains(textSearch.CustName));
            }
            if (!string.IsNullOrEmpty(textSearch.Industry))
            {
                querySearch = lang.Equals("vi") ? querySearch.Where(x => x.cust.IndustryName.Contains(textSearch.Industry)) : querySearch.Where(x => x.cust.IndustryNameEn.Contains(textSearch.Industry));
            }
            if (!string.IsNullOrEmpty(textSearch.CusOpenDate))
            {
                List<string> listFilter = textSearch.CusOpenDate.Split('-').ToList();
                FromDateCompare = DateTime.ParseExact(listFilter.FirstOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                ToDateCompare = DateTime.ParseExact(listFilter.LastOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                querySearch = querySearch.Where(x => x.cust.StartCurStatus.Value >= FromDateCompare && x.cust.StartCurStatus.Value <= ToDateCompare);
            }
            if (!string.IsNullOrEmpty(textSearch.CusStatus) && textSearch.CusStatus != "2")
            {
                querySearch = querySearch.Where(x => x.cust.Status.Equals(textSearch.CusStatus));
            }
            query = querySearch.OrderBy(x => new { x.branch.Region, x.branch.BranchId, x.cust.Dao }).Select(x => x.cust);
            totalRecord = query.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        #endregion
        #region Top 10
        public List<CustomerTop10> RetrieveCustomerTop10(UserRecord dao, int type, FilterRecord filter)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerTop10s
                        where x.DaoCif != null
                        select x;
            switch (dao.GroupIdentifier)
            {
                case "1":
                    break;
                case "2":
                    query = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { cust = x, branch = y }).Where(x => x.branch.Region == dao.Zone).Select(x => x.cust);
                    break;
                case "3":
                    query = query.Join(data.Branchs, x => x.BranchId, y => y.BranchId, (x, y) => new { cust = x, branch = y }).Where(x => x.branch.BranchNameSme == dao.Branch).Select(x => x.cust);
                    query = query.Where(x => filter.Dao.Contains(x.DaoCif));
                    break;
                case "4":
                    query = query.Where(x => x.DaoCif.ToUpper() == dao.Dao.ToUpper());
                    break;
                default:
                    break;
            }
            if (type == 2)
            {
                query = query.OrderBy(x => x.Toi).Take(10);
            }
            else
            {
                query = query.OrderByDescending(x => x.Toi).Take(10);
            }

            return query.ToList();
        }
        #endregion
        #region Customer Finance
        public List<CustomerFinanceInfo> RetrieveCustomerFinanceInfoByCif(string cif)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerFinanceInfos
                        where x.Cif == cif
                        select x;
            return query.ToList();
        }
        public List<CustomerLimitInfo> RetrieveCustomerLimitInfoByCif(string cif)
        {
            var data = repository.DbContext as CustomerEntities;
            var query = from x in data.CustomerLimitInfos
                        where x.Cif == cif
                        orderby new { x.GroupTypeLimit, x.TypeOrder }
                        select x;
            return query.ToList();
        }
        #endregion
    }
}
